﻿using System;
using System.Collections.Generic;
using System.IO;
using GeoAPI.Geometries;
using YJKGridTopologyCal.Noding;

namespace YJKGridTopologyCal.GeometriesGraph
{
	public class EdgeList
	{
		public void Remove(Edge e)
		{
			this._edges.Remove(e);
		}

		public void Add(Edge e)
		{
			this._edges.Add(e);
			OrientedCoordinateArray key = new OrientedCoordinateArray(e.Coordinates);
			this._ocaMap.Add(key, e);
		}

		public void AddAll(IEnumerable<Edge> edgeColl)
		{
			foreach (Edge e in edgeColl)
			{
				this.Add(e);
			}
		}

		public IList<Edge> Edges
		{
			get
			{
				return this._edges;
			}
		}

		public Edge FindEqualEdge(Edge e)
		{
			OrientedCoordinateArray key = new OrientedCoordinateArray(e.Coordinates);
			Edge result;
			this._ocaMap.TryGetValue(key, out result);
			return result;
		}

		public IEnumerator<Edge> GetEnumerator()
		{
			return this._edges.GetEnumerator();
		}

		public Edge this[int index]
		{
			get
			{
				return this.Get(index);
			}
		}

		public Edge Get(int i)
		{
			return this._edges[i];
		}

		public int FindEdgeIndex(Edge e)
		{
			for (int i = 0; i < this._edges.Count; i++)
			{
				if (this._edges[i].Equals(e))
				{
					return i;
				}
			}
			return -1;
		}

		public void Write(StreamWriter outstream)
		{
			outstream.Write("MULTILINESTRING ( ");
			for (int i = 0; i < this._edges.Count; i++)
			{
				Edge edge = this._edges[i];
				if (i > 0)
				{
					outstream.Write(",");
				}
				outstream.Write("(");
				Coordinate[] coordinates = edge.Coordinates;
				for (int j = 0; j < coordinates.Length; j++)
				{
					if (j > 0)
					{
						outstream.Write(",");
					}
					outstream.Write(coordinates[j].X + " " + coordinates[j].Y);
				}
				outstream.WriteLine(")");
			}
			outstream.Write(")  ");
		}

		private readonly List<Edge> _edges = new List<Edge>();

		private readonly IDictionary<OrientedCoordinateArray, Edge> _ocaMap = new SortedDictionary<OrientedCoordinateArray, Edge>();
	}
}
